/**
 * Copyright millionhere
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may see it at...
 *      http://www.apache.org/licenses/LICENSE-2.0
 */

package info.millionhere.keepsilent;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class AddNewRuleActivity extends Activity implements OnClickListener{
    
    static final String TAG_ADDRESS = "ADDRESS";
    static final String TAG_COMMENT = "COMMENT";
    static final String TAG_POSITION = "POSITION";
    
    static final int TAG_REQUESTCODE_PICKONECONTACT = 1;
    static final int TAG_REQUESTCODE_PICKUPCONVERSATION = 2;
    
    private Button mButtonSave;
    private Button mButtonContact;
    private Button mButtonMessage;
    private EditText mEditTextAddress;
    private EditText mEditTextComment;
    
    private int editingPosition;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add);
        
        mButtonSave = (Button)findViewById(R.id.button_add_save);
        mButtonContact = (Button)findViewById(R.id.button_add_contact);
        mButtonMessage = (Button)findViewById(R.id.button_add_message);
        
        mEditTextAddress = (EditText)findViewById(R.id.edit_address);
        mEditTextComment = (EditText)findViewById(R.id.edit_comment);
        
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null){
            mEditTextAddress.setText(bundle.getString(TAG_ADDRESS));
            mEditTextComment.setText(bundle.getString(TAG_COMMENT));
            editingPosition = bundle.getInt(TAG_POSITION);
        }

        mButtonSave.setOnClickListener(this);
        mButtonContact.setOnClickListener(this);
        mButtonMessage.setOnClickListener(this);
    }
    
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.button_add_save:
        	ButtonSaveClicked();
                break;
            case R.id.button_add_contact:
        	ButtonContactClicked();
                break;
            case R.id.button_add_message:
        	ButtonMessageClicked();
                break;
            default:
        	break;
        }
    }
    
    private void ButtonSaveClicked(){
	if (mEditTextAddress.getText().toString().trim().equals("")){
	}
	else{
	    String address = mEditTextAddress.getText().toString();
	    if (!DealWithCountryCallingCodes.bHaveCountryCallingCodes(address)){
		    address = (DealWithCountryCallingCodes.transCountryIsoToCountryCallingCode(((TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkCountryIso())) + address;
		}
        	Intent intent = new Intent();
        	Bundle bundle = new Bundle();
        	bundle.putString(TAG_ADDRESS, address);
        	bundle.putString(TAG_COMMENT, mEditTextComment.getText().toString());
        	bundle.putInt(AddNewRuleActivity.TAG_POSITION, editingPosition);
        	intent.putExtras(bundle);
        	this.setResult(RESULT_OK, intent);
	}
	this.finish();
    }
    
    private void ButtonContactClicked(){
	Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
	startActivityForResult(intent, TAG_REQUESTCODE_PICKONECONTACT);
    }
    
    private void ButtonMessageClicked(){
	startActivityForResult(new Intent(this, PickupConversationActivity.class), TAG_REQUESTCODE_PICKUPCONVERSATION);
    }
    
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 
	switch (requestCode){
	case TAG_REQUESTCODE_PICKONECONTACT:
	    if (resultCode == RESULT_OK)
	    {
		
		Uri uri = intent.getData();
		ContentResolver contentResolver = getContentResolver();
		Cursor contactsCursor = contentResolver.query(uri, null, null, null, null);
		
		int idColumnIndex = -1;
		int displayNameColumnIndex = -1;
		
		try {idColumnIndex = contactsCursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID);}catch(Exception e){}
		try {displayNameColumnIndex = contactsCursor.getColumnIndexOrThrow(ContactsContract.Data.DISPLAY_NAME);}catch(Exception e){}
		
		try {
		//just deal with the first one
		if (contactsCursor.moveToFirst()) {
        		if (displayNameColumnIndex != -1){
        		    String name = contactsCursor.getString(displayNameColumnIndex);
        		    mEditTextComment.setText(name);
        		}
        		
        		long id = contactsCursor.getLong(idColumnIndex);
        		//just deal with the first MOBILE phone number either
        		Cursor phonesCursor = getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				null,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID
						+ " = " + id +" and " + ContactsContract.CommonDataKinds.Phone.TYPE + " = " + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, null, null);
        		if (phonesCursor.moveToFirst()){
        		    mEditTextAddress.setText(phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
        		}
		}
		}
		catch(Exception e){}
	    }
	    break;
	case TAG_REQUESTCODE_PICKUPCONVERSATION:
	    if (resultCode == RESULT_OK)
	    {
		mEditTextAddress.setText(intent.getExtras().getString(PickupConversationActivity.TAG_ADDRESS));
		mEditTextComment.setText(intent.getExtras().getString(PickupConversationActivity.TAG_MESSAGE));
	    }
	    break;
	default:
	    break;
	}
    }
}
